﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OrderingSystem.Domain
{
    public abstract class Entity <T> where T: Entity<T>
    {
        public int ID { get; private set; }

        private int? oldHashCode;

        public override bool Equals(object obj)
        {
            var other = obj as T;
            if (other == null)
            {
                return false;
            }

            var thisIsNew = Equals(ID, 0);
            var otherIsNew = Equals(other.ID, 0);

            if ((thisIsNew == true) && (otherIsNew == true))
            {
                return ReferenceEquals(this, other);
            }

            return ID.Equals(other.ID);
        }

        public override int GetHashCode()
        {
            if (oldHashCode.HasValue == true)
            {
                return oldHashCode.Value;
            }
            var thisIsNew = Equals(ID, 0);

            if (thisIsNew == true)
            {
                oldHashCode = base.GetHashCode();
                return oldHashCode.Value;
            }
            return ID.GetHashCode();
        }
    }
}
